package com.oscar.ehome.view.pageview;

import android.graphics.Color;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.oscar.ehome.R;
import com.oscar.ehome.base.C;
import com.oscar.ehome.base.activity.BasesActivity;
import com.oscar.ehome.bean.pagebean.StudyListBean;
import com.oscar.ehome.presenter.BasePresenter;
import com.oscar.ehome.utils.database.DataBaseDAO;
import com.oscar.ehome.utils.dowload.dowload.DownloadManager;
import com.oscar.ehome.utils.dowload.dowload.OnDownload;
import com.oscar.ehome.utils.dowload.entity.FileInfo;
import com.oscar.ehome.utils.dowload.progressbar.RoundProgressBar;
import com.oscar.ehome.utils.pullrefresh.PullToRefreshBase;
import com.oscar.ehome.utils.pullrefresh.PullToRefreshListView;
import com.oscar.ehome.utils.system.SystemConfigFactory;
import com.oscar.ehome.utils.util.CommonUtils;
import com.oscar.ehome.utils.util.ToastUtil;
import com.oscar.ehome.view.pageview.adapter.DownloadAdapter;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by oscar
 * author: MengWanhe
 * date: On 2017/7/14
 * 下载列表页
 */

public class DownloadListActivity extends BasesActivity implements DownloadAdapter.OnClickedsListener, PullToRefreshBase.OnRefreshListener {

    /**
     * 关闭
     */
    @BindView(R.id.close_img)
    ImageView closeImg;
    /**
     * listview
     */
    @BindView(R.id.downlist_listview)
    PullToRefreshListView downlistListview;
    /**
     *
     */
    @BindView(R.id.download_title)
    RelativeLayout downloadTitle;

    DownloadAdapter adapter;
    ArrayList<StudyListBean> learnList = new ArrayList<>();
    StudyListBean studyListBean = null;
    DataBaseDAO dataBaseDAO;//数据库


    /**
     * 进度条
     */
    private ProgressBar progressBar = null;

    /**
     * 下载的文件详情
     */
    public FileInfo info;
    public String videoUrl = "";//下载地址
    public String fileName = "";//文件名字
    public String ids = "";//文件ID
    public int id = 0;//
    public String localPath = "";//文件存放路径
    int page = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_downlist);
        ButterKnife.bind(this);
        downloadTitle.setBackgroundColor(Color.parseColor(SystemConfigFactory.getInstance(DownloadListActivity.this).getSystemConfig().getColor()));
        initView();
        initData();
        onClick();
        dataBaseDAO = new DataBaseDAO(this);
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    /**
     * 初始化
     */
    public void initView() {
        String list = getIntent().getStringExtra("listData");
        try {
            learnList = CommonUtils.fromJsonArray(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        localPath = CommonUtils.getSDCardRootPath(DownloadListActivity.this) + C.video;// 文件存储路径，sd卡路径
    }

    /**
     * 加载数据
     */
    public void initData() {
        if (learnList.size() > 0) {
            undowload();
            adapter = new DownloadAdapter(DownloadListActivity.this, learnList);
            downlistListview.setAdapter(adapter);
            adapter.setOnClicksListener(this);
        }
    }

    @OnClick(R.id.close_img)
    public void onViewClicked() {
        finish();
    }

    /**
     * 点击
     */
    public void onClick() {
        downlistListview.setPullLoadEnabled(true);
        downlistListview.setOnRefreshListener(this);
    }

    @Override
    public void onClicks(int postion, int download, RoundProgressBar progressBar) {

        StudyListBean b = learnList.get(postion);
        int state = b.getVideoState();

        switch (download) {
            case 1://点击开始下载
                if (state == 0) {
                    videoUrl = learnList.get(postion).getDownloadurl();
                    fileName = learnList.get(postion).getMediaFile();
                    ids = learnList.get(postion).getId();
                    id = learnList.get(postion).getIds();
                    if (videoUrl != null && !"".equals(videoUrl)) {
                        dowload_file(postion, learnList.get(postion), progressBar);
                    } else {
                        ToastUtil.show(DownloadListActivity.this, "下载路径不存在");
                    }
                }
                break;
            case 2://继续下载
                if (state == 2) {
                    if (CommonUtils.isNetConn(DownloadListActivity.this)) {// 判断是否有网
                        videoUrl = C.qiniu_ip + learnList.get(postion).getMediaFile();
                        fileName = learnList.get(postion).getMediaFile();
                        ids = learnList.get(postion).getId();
                        id = learnList.get(postion).getIds();
                        if (videoUrl != null && !"".equals(videoUrl)) {
                            dowload_file(postion, learnList.get(postion), progressBar);
                        } else {
                            ToastUtil.show(DownloadListActivity.this, "下载路径不存在");
                        }
                    } else {
                        ToastUtil.show(DownloadListActivity.this, "网络不给力");
                    }
                }
                break;
            case 3://正在下载时，点击暂停
                videoUrl = C.qiniu_ip + learnList.get(postion).getMediaFile();
                fileName = learnList.get(postion).getMediaFile();
                ids = learnList.get(postion).getId();
                id = learnList.get(postion).getIds();
                puseDowload_file(learnList.get(postion));
                break;
        }
    }

    /**
     * 下载的状态
     */
    public void undowload() {// 已下载
        for (int i = 0; i < learnList.size(); i++) {
            fileName = learnList.get(i).getMediaFile();
            if (fileName != null) {
                learnList.get(i).setDownloadurl(C.qiniu_ip + fileName);
            }
            if (CommonUtils.GetVideoFileName(CommonUtils.getSDCardRootPath(DownloadListActivity.this) + C.video + fileName)) {
                // 已下载
                learnList.get(i).setIsFinsh("1");
                learnList.get(i).setVideoState(3);
            } else {
                // 未下载
                learnList.get(i).setIsFinsh("0");
                learnList.get(i).setVideoState(0);
            }
            learnList.get(i).setIds(i + 1);
            learnList.get(i).setVideo_Path(CommonUtils.getSDCardRootPath(DownloadListActivity.this) + C.video + fileName);
        }
    }

    /**
     * 下载文件的方法
     */
    public void dowload_file(int postion, StudyListBean bean, RoundProgressBar progressBar) {
        // 下载
        learnList.get(postion).setVideoState(1);
        info = new FileInfo(id, bean.getDownloadurl(), learnList.get(postion).getMediaFile(), 0, 0);
        final OnDownloadImpl impl = new OnDownloadImpl(progressBar, postion, bean);
//        adapter.isDownloadRefresh(1, postion);// 判断是点击的正常的更新adapter
        String localPath = CommonUtils.getSDCardRootPath(DownloadListActivity.this) + C.video;// 文件存储路径，sd卡路径
        DownloadManager.instance(DownloadListActivity.this).startDownload(info.getUrl(), localPath, learnList.get(postion).getMediaFile(), impl, ids, 1,
                0, progressBar); // 开始下载

        ToastUtil.show(DownloadListActivity.this, "开始下载");
    }

    /**
     * 暂停文件的方法
     */
    public void puseDowload_file(StudyListBean bean) {
        info = new FileInfo(id, bean.getDownloadurl(), 0, 0);
        DownloadManager.instance(DownloadListActivity.this).pauseDownload(info.getUrl()); // 暂停下载
        bean.setVideoState(2);

    }

    /**
     * 下载回调监听类
     */
    class OnDownloadImpl implements OnDownload {
        public RoundProgressBar pb; // 进度条
        public int position; // 列表位置
        public StudyListBean b;

        public OnDownloadImpl(RoundProgressBar pb, int posision, StudyListBean b) {
            this.pb = pb;
            this.b = b;
            this.position = posision;
        }

        /**
         * 下载中
         */
        @Override
        public void onDownloading(String retUrl, int finished, String bookid, RoundProgressBar pb) {
            StudyListBean b = learnList.get(position);
            if (b.getVideoState() == 2) {

            } else {
                pb.setProgress(finished);
                b.setVideoState(1);
            }
        }

        /**
         * 下载完成
         */
        @Override
        public void onDownloadFinished(File downloadFile, int isfinshed) {
            ToastUtil.show(DownloadListActivity.this, "下载完成");
            CommonUtils.isVideo = 0;

            StudyListBean b = learnList.get(position);
            b.setSize(100);
            b.setVideoState(3);
            adapter.notifyDataSetChanged();

            //插入数据库
            Map<String, Object> datas = new HashMap<String, Object>();// 存储用户反馈信息
            datas.put("title", b.getTitle());
            datas.put("imgdata", C.qiniu_ip + b.getSmallImg());
            String sizes = CommonUtils.getFileOrFilesSize(b.getVideo_Path(), 3);
            datas.put("size", sizes);
            datas.put("filename", b.getVideo_Path());
            dataBaseDAO.insert("fileDownload", datas);
        }

        /**
         * 是否连接网络
         */
        @Override
        public void onNetwork(boolean flag) {// 判断是否有网络
            // TODO Auto-generated method stub
            if (!flag) {
                DownloadManager.instance(DownloadListActivity.this).pauseDownload(C.qiniu_ip + b.getMediaFile()); // 暂停下载
                b.setVideoState(2);
            } else {
                String localPath = CommonUtils.getSDCardRootPath(DownloadListActivity.this) + C.video;// 文件存储路径，sd卡路径
                final OnDownloadImpl impl = new OnDownloadImpl(pb, position, b);
                b.setVideoState(1);
                DownloadManager.instance(DownloadListActivity.this).startDownload(C.qiniu_ip + b.getMediaFile(), localPath, b.getMediaFile(), impl, b.getId(), 1,
                        0, pb); //
            }
        }

        @Override
        public void onStrartDownloading(String url, String bookid) {
            // TODO Auto-generated method stub
//            adapter.notifyDataSetChanged();
        }

        @Override
        public void onErroy(String bookid) {
            // TODO Auto-generated method stub
            if (ids.equals(bookid)) {
                ToastUtil.show(DownloadListActivity.this, "下载失败");
            }
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        downlistListview.onPullDownRefreshComplete();
        downlistListview.onPullUpRefreshComplete();
        adapter.setmData(learnList);
//        adapter.notifyDataSetChanged();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        downlistListview.onPullDownRefreshComplete();
        downlistListview.onPullUpRefreshComplete();
    }


}
